# Create your views here.
#from django.http import HttpResponseRedirect
from django.http import Http404, HttpResponse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from hashlib import md5
from livesociety.actions.models import User, Status, PrivateMsg, Comment
from operator import itemgetter #import to sort the states_list
import datetime




def main (request):
    context = {}
        
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')
        
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            
            #Current User
            context['c_user'] = USR
            #Current user's friends
            context['cu_friends'] = USR.friends.all()
            #Current user's states sorted by id (high to low)
            try:
                context['last_status'] = USR.states.order_by('-id')[0]
            except:
                context['last_status'] = ""
            context['cu_states'] = USR.states.order_by('-id')
            #Current user's comments sorted by id (high to low)
            context['cu_comments'] = USR.comments.order_by('-id')
            
            #This is a list sorted by id (high to low) of current user's friends states
            states_list =[]
            for friend in USR.friends.all():
                #dictionary['f_name'] = friend.name
                #dictionary['f_avatar'] = friend.avatar
                #dictionary['f_name'] = friend.lastname
                for estado in friend.states.all():
                    dictionary ={}
                    dictionary['s_id'] = estado.id
                    dictionary['s_author'] = estado.author
                    dictionary['s_content'] = estado.content
                    dictionary['s_date'] = estado.date
                    dictionary['s_time'] = estado.time
                    states_list.append(dictionary)
            try:    
                sorted(states_list, key=itemgetter('s_id'))
                states_list.reverse()
                context['states_list'] = states_list
            except:
                pass
            return render_to_response ('inner.html',RequestContext(request,context))
        else:
            return redirect('/')
    else:
        return redirect('/')

def sendstatus (request):
    context = {}
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')
        
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            try:
                s_content = request.POST['status']
                s_author = request.POST['author']
                s_author = User.objects.get(mail = s_author)
            except:
                context['msgbox'] = 'Ha fallado el envio del estado ya que no se recibieron datos, intentalo nuevamente.'
                return HttpResponse(context['msgbox'])
            try:
                newstatus = Status(author = s_author, content = s_content)
                newstatus.save()
                return None
            except:
                context['msgbox'] = 'Ha fallado el envio del estado, intentalo nuevamente.'
                return context['msgbox']
        else:
            context['msgbox'] = 'Usted no esta logueado'
            return HttpResponse(context['msgbox'])
    else:
        return None
    
def settings(request):
    context = {}
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')
        
        context['c_user'] = USR
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            try:
                return render_to_response('settings.html', RequestContext(request,context))
            except:
                context['msgbox'] = 'Error al mostrar las preferencias, intentalo nuevamente'
                return render_to_response('settings.html', RequestContext(request,context))
        else:
            return redirect('/')
    else:
        return redirect('/')
    
def updatesettings(request):
    context = {}
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
            
        except:
            return redirect('/logout')
        
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            try:
                name = request.POST['name']
                lastname = request.POST['lastname']
                gender = request.POST['gender']
                bdate = request.POST['birthday']
                if len(bdate) is 10: 
                    fnac = bdate.split('/')
                    fnac_day = int(fnac[0])
                    fnac_month = int(fnac[1])
                    fnac_year = int(fnac[2])
                    context['persistency'] = True
                    context['msgbox'] = "inside code!"
                    USR.birthday = datetime.date(fnac_year, fnac_month, fnac_day)
                try:
                    avatar = request.FILES['avatar']
                    USR.UpdateAvatar(avatar)
                    
                except:
                    #sin actualizar avatar
                    pass
                bio = request.POST['bio']
                password = request.POST['password']
                if password > 3:
                    USR.password = md5(password).hexdigest()
                USR.name = name
                USR.lastname = lastname
                USR.gender = gender
                USR.bio = bio
                USR.save()
                context['msgbox'] = ' Datos actualizados!'
                return redirect('/settings')
            except:
                #context['msgbox'] = 'Error al actualizar los datos, intentalo nuevamente'
                return redirect('/settings')
        else:
            return redirect('/')
    else:
        return redirect('/')
    
    
def friends(request):
    context = {}
        
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')

        if request.COOKIES['session_key'] == USR.sessions.get().key:
            try:
                context['c_user'] = USR
                context['cu_friends'] = USR.friends.all()
                context['cu_requests'] = USR.requests.all()
                return render_to_response('friends.html', RequestContext(request,context))
            except:
                context['msgbox'] = 'Error al mostrar amigos, intentalo nuevamente'
                return render_to_response('friends.html', RequestContext(request,context))
        else:
            return redirect('/')
    else:
        return redirect('/')
    
def acceptrequest(request):
    context = {}
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            
            mail_toAccept = request.POST['m_toaccept']
            try:
                u_toAccept = USR.requests.get(mail = mail_toAccept)
                USR.friends.add(u_toAccept)
                USR.requests.remove(u_toAccept)
                USR.save()
                context['msgbox']='Amigo agregado'
                return HttpResponse(context['msgbox'])
            except:
                context['msgbox']='Error al aceptar amigo'
                return HttpResponse(context['msgbox'])
        else:
            return None
    else:
        return None
    
def addfriend(request):
    context = {}
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')
        
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            try:
                f_mail = request.POST['friendmail']
                UT_request = User.objects.get(mail=f_mail)
                UT_request.requests.add(USR)
                context['msgbox']= 'Peticion de amistad enviada con exito'
                return HttpResponse(context['msgbox'])
                
            except:
                context['msgbox']= 'Error al agregar amigo'
                return HttpResponse(context['msgbox'])
        else:
            return None
    else:
        return None
    
def messages(request):
    context = {}
        
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
            MSGS = USR.privates_in.all()
        except:
            return redirect('/logout')
        context['c_user'] = USR
        context['cu_privates'] = MSGS
        return render_to_response('messages.html', RequestContext(request,context))
    else:
        return redirect('/')  
    
def sendmsg(request):
    context = {}
        
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
            context['msgbox'] = 'El usuario '+request.POST['friendmail']+' no existe'
            DEST = User.objects.get(mail=request.POST['friendmail'])
        except:
            return HttpResponse(context['msgbox'])
        try:
            MSG = request.POST['msg']
            msg = PrivateMsg(author=USR, recipient=DEST, content=MSG, readed=False)
            msg.save()
            context['msgbox'] = 'Mensaje enviado!'
            return HttpResponse(context['msgbox'])
        except:
            context['msgbox'] = 'Error C-8 al enviar mensaje!'
            return HttpResponse(context['msgbox'])
    else:
        return None
      
def viewuser(request, f_id):
    context = {}
        
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
            try:
                u_friend = User.objects.get(id=f_id)
                try:
                    USR.friends.get(id=f_id)
                    context['f_name'] = u_friend.name
                    context['f_lastname'] = u_friend.lastname
                    context['f_avatar'] = u_friend.avatar
                    context['f_bio'] = u_friend.bio
                    context['f_mail'] = u_friend.mail
                    context['f_gender'] = u_friend.gender
                    context['f_states'] = u_friend.states.order_by('-id')
                    context['arefriends'] = True
                    return render_to_response('viewuser.html', RequestContext(request,context))
                except:
                    context['arefriends'] = False
                    context['f_mail'] = u_friend.mail
                    context['f_gender'] = u_friend.gender
                    context['f_name'] = u_friend.name
                    context['f_avatar'] = u_friend.avatar
                    context['f_lastname'] = u_friend.lastname
                    context['f_bio'] = u_friend.bio
                    return render_to_response('viewuser.html', RequestContext(request,context))
            except:
                context['persistency'] = True
                context['msgbox'] = 'No existe ese usuario'
                return redirect('/main')
        except:
            return redirect('/logout')
    else:
        return redirect('/')
    
def comment(request):
    context = {}
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'): 
        try:
            USR = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            return redirect('/logout')
        
        if request.COOKIES['session_key'] == USR.sessions.get().key:
            try:
                state_id = request.POST['s_id']
                comment_content = request.POST['c_content']
            except:
                #no se reciben las variables por post por lo que se manda error
                context['msgbox'] = 'Ha fallado el comentario ya que no se recibieron datos, intentalo nuevamente.'
                #return render_to_response('inner.html',RequestContext(request, context))
                return HttpResponse(context['msgbox'])
            try:
                state = Status.objects.get(id=state_id)
                newcomment = Comment(author = USR, content = comment_content, status=state)
                newcomment.save()
                context['msgbox'] = 'El comentario se ha enviado exitosamente'
                #return render_to_response('inner.html',RequestContext(request, context))
                return HttpResponse(context['msgbox'])
            except:
                #no se registra el estatus por lo que se manda error
                context['msgbox'] = 'Ha fallado el envio del estado, intentalo nuevamente.'
                return HttpResponse(context['msgbox'])
        else:
            return None
    else:
        return None
    
def setasreaded(request):
    if request.COOKIES.has_key('user_mail') and request.COOKIES.has_key('session_key'):
        try:
            user = User.objects.get(mail=request.COOKIES['user_mail'])
        except:
            raise Http404
    try:
        msg_id = request.GET['msg_id']
    except:
        raise Http404
    
    try:
        msg = PrivateMsg.objects.get(id=msg_id)
        if msg.recipient.id is user.id:
            msg.readed = True
            msg.save()
        else:
            return redirect('/')
        
        return redirect('/')
    except:
        raise Http404